#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project : gtmsAutoTestProject 
@File    : toolsControl.py
@IDE     : PyCharm 
@Author  : Mario
@Date    : 2022/4/24 18:46 
@Describe: 常用工具类
"""
import os
import sys
import time
import json
import random
import string
import jsonpath
import requests

from Comm.logUtils.logControl import LogHandler

logger = LogHandler().get_logger()


class ToolsHandler:

    @staticmethod
    def get_random(length=32):
        """
        生成指定位数随机数
        :param length: 随机数长度，默认32位
        :return:
        """
        randoms = ''.join(random.sample(string.digits + string.ascii_letters, length))
        logger.debug('生成{}位随机数成功,随机数:{}'.format(length, randoms))
        return randoms

    @staticmethod
    def get_json_result(jsonContent, key):
        """
        提取JSON指定内容
        :param jsonContent: JSON内容
        :param key: 提取操作符
        :return: 提取内容
        """
        if type(jsonContent) == str:
            responses = json.loads(jsonContent)
        else:
            # 先把传入的值转换为json格式
            responses = json.loads(jsonContent.content)
        # 将需要提取的值提取出来
        result = jsonpath.jsonpath(responses, "{}".format(key))
        logger.debug("提取指定参数成功,提取表达式:{},提取值:{}".format(key, result))
        if result:
            if len(result) == 1:
                return result[0]
            return result

    @staticmethod
    def get_timestamp():
        """
        生产当前时间的时间戳
        :return:
        """
        timestamp = str(int((time.time() * 1000)))
        logger.debug('生成当前时间戳成功,时间戳:{}'.format(timestamp))
        return timestamp

    @staticmethod
    def ice_time(min_time=0, max_time=10):
        """
        生成随机等待时间
        :param min_time: 最小值
        :param max_time: 最大值
        :return:
        """
        random_ice_time = random.randint(min_time, max_time)
        logger.debug('生成随机等待时间成功！等待时间:{}S;'.format(random_ice_time))
        time.sleep(random_ice_time)

    @staticmethod
    def delete_specify_format_document(path, format):
        """
        删除指定格式的文件 (谨慎操作！！！！！)
        :param path: 文件路径
        :param format: 文件格式,如: [.txt]
        :return:
        """
        # os.walk()返回元组，包含三个元素:每次遍历的路径名、路径下子目录列表、目录下文件列表
        for root, dirs, files in os.walk(path):
            for name in files:
                if name.endswith(format):  # 指定要删除的文件格式
                    os.remove(os.path.join(root, name))
                    logger.info("正在删除{}文件夹内{}格式文件,文件名:{}".format(root, format, name))

    @staticmethod
    def exit_program():
        """
        强制退出当前运行程序
        :return:
        """
        logger.debug('正在退出当前执行程序')
        sys.exit()

    @staticmethod
    def get_now_time():
        """
        获取当前时间
        :return:%Y-%m-%d %H:%M:%S-格式时间
        """
        now_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(time.time())))
        return now_time

    @staticmethod
    def get_moon_start_time():
        """
        获取本月开始时间
        :return:
        """
        start_time = time.strftime('%Y-%m' + '-01 00:00:00', time.localtime(int(time.time())))
        return start_time

    @staticmethod
    def get_json_valus(json_obj, key):
        """
        获取json对应值
        :param json_obj: json字符串
        :param key: 键
        :return:
        """
        valus = dict(json_obj)  # 转化成字典类型
        return valus[key]

    @staticmethod
    def get_shopCode(brand_code):
        """
        根据品牌获取门店编码
        :param brand_code: 品牌编码
        :return: 门店编码
        """
        if brand_code == '823882':
            shop_code = '5999'
        elif brand_code == '823883':
            shop_code = '6999'
        elif brand_code == '823884':
            shop_code = '8499'
        elif brand_code == '823885':
            shop_code = '8999'
        else:
            return False
        return shop_code

    @staticmethod
    def get_request_id(length=14):
        """
        生成request_id
        :param length: 随机数长度
        :return:
        """
        request_id = ''.join(random.choices(string.ascii_uppercase + string.digits, k=length))
        return request_id

    @staticmethod
    def load_with_url(input_url, output_file):
        """
        下载文件
        :param input_url: 下载网址
        :param output_file: 本地文件路径
        :return:
        """
        f = requests.get(input_url)
        # 下载文件
        with open(output_file, "wb") as file:
            file.write(f.content)


if __name__ == '__main__':
    for i in range(10):
        ToolsHandler.ice_time(1, 5)
